package experiment.e09.code;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/12/1 14:52
 * @package experiment.e09.code
 * @description 文件说明
 */

//生产者线程
class Producer extends Thread {


    private Buffer buffer;
    private int number;

    public Producer(Buffer buffer, int number) {
        this.buffer = buffer;
        this.number = number;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            buffer.put(1);
//            System.out.println("生产者#" + number + "生产");

        }
    }

}

//消费者线程
class Consumer extends Thread {
    private Buffer buffer;
    private int number;


    public Consumer(Buffer buffer, int number) {
        this.buffer = buffer;
        this.number = number;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            int v = buffer.get();
//            System.out.println("消费者#" + number + "消费" + v);

        }
    }
}
//有界缓冲区类Buffer.java文件内容如下:

//生产者与消费者共享的缓冲区,必须实现读,写的同步
class Buffer {
    private int contents;
    private boolean available = false;

    public synchronized int get() {
        while (!available) {
            try {
                this.wait();
            } catch (InterruptedException exc) {
            }
        }
        int value = contents;
        //消费者取出内容,改变存取控制available
        available = false;
        System.out.println("取出" + contents);
        this.notifyAll();
        return value;
    }

    public synchronized void put(int value) {
        while (available) {
            try {
                this.wait();
            } catch (InterruptedException exc) {
            }
        }
        contents = value;
        //生产者放入内容,改变存取控制available
        available = true;
        System.out.println("放入" + contents);
        this.notifyAll();
    }
}

//演示生产者-消费者问题的主程序
class ProducerConsumerProblem {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        new Producer(buffer, 101).start();
        new Consumer(buffer, 200).start();
        new Consumer(buffer, 201).start();

    }
}

